package com.sunyy.wordparser.util;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

public class PoiExcelUtil {
    public static void writeDataToExcel(String filePath, List<Map<String, String>> data) throws IOException, FileNotFoundException {
        // 创建一个新的工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("DataSheet");

        // 找到所有的标题
        List<String> headers=new ArrayList<>();
        for (Map<String, String> datum : data) {
            Set<String> strings = datum.keySet();
            for (String string : strings) {
                if (!headers.contains(string)){
                    headers.add(string);
                }
            }

        }
        // 自动提取标题行
        //Set<String> headers = data.isEmpty() ? Set.of() : data.get(0).keySet();
        Row headerRow = sheet.createRow(0);
        int colIndex = 0;
        for (String header : headers) {
            Cell cell = headerRow.createCell(colIndex++);
            cell.setCellValue(header);
        }

        // 写入数据行
        int rowIndex = 1;
        for (Map<String, String> row : data) {
            Row dataRow = sheet.createRow(rowIndex++);
            colIndex = 0;
            for (String header : headers) {
                Cell cell = dataRow.createCell(colIndex++);
                if (row.containsKey(header)){
                    String value = row.get(header);
                    if (value != null) {
                        cell.setCellValue(value);
                    }
                }
            }
        }

        // 写入文件
        try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
            workbook.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            workbook.close();
        }
    }
}
